<?php

final class DatabaseIterator implements Iterator
{
	private $resource;
	private $db;
	private $num;
	private $cursor;
	private $row;
	
	public function __construct(Database $db, $resource) {
		$this->db       = $db;
		$this->resource = $resource;
		
		$this->num = mysql_num_rows($resource);
		
		if ($this->num === false) {
			throw new DatabaseException('Wrong result resource');
		}
	}
	
	public function rewind() {
		if ($this->num != 0) {
			$this->db->seek($this->resource, 0);
			$this->row = $this->db->fetch($this->resource);
			$this->cursor = 0;
		}
	}
	
	public function current() {
		return $this->row;
	}
	
	public function key() {
		return $this->cursor;
	}
	
	public function next() {
		$this->cursor++;
		$this->row = $this->db->fetch($this->resource);
	}
	
	public function valid() {
		return $this->cursor < $this->num;
	}
}
